package com.xml2db;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

@Component("dBWriter")
public class DBWriter {

	private Logger logger = LoggerFactory.getLogger(DBWriter.class);

	@Autowired
	private SqlGenerator sqlGenerator;// 这里倒时改回用接口的形式，方便扩展
	@Autowired
	private JdbcTemplate jdbcTemplate;

	// TODO:
	// 1.先判断该表名是否已存在，若存在则先删除该表，然后根据表名，字段值集合，类型集合创建数据表
	// 2.将数据集合写进数据库
	public void writeToDB(List<DBTable> dbTables) {

		for (DBTable table : dbTables) {
			String dropTableSQL = sqlGenerator.dropTableSQL(table);
			String createTableSQL = sqlGenerator.createTableSQL(table);
			String insertSQL = sqlGenerator.insertSQL(table);
			try {
				logger.info("开始写入{}数据表数据", table.getTableName());
				jdbcTemplate.execute(dropTableSQL);
				jdbcTemplate.execute(createTableSQL);
				jdbcTemplate.batchUpdate(insertSQL, table.getDatas());
			} catch (Exception e) {
				logger.error("{}写入数据库失败", table.getTableName());
				e.printStackTrace();
			}

		}
	}
}
